package com.haima.sage.bigdata.api.common;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class DateUtils {
    private static final Logger LOG = LogManager.getLogger(DateUtils.class);
    private Calendar calendar = Calendar.getInstance();
    private String pattern = "yyyyMMdd";
    private SimpleDateFormat sdf = null;
    private static final HashMap<String, Integer> sample = new HashMap<String, Integer>();
    {
        sample.put("yyyy", Calendar.YEAR);
        sample.put("yy", Calendar.YEAR);
        sample.put("yyyy/MM", Calendar.MONTH);
        sample.put("yyyy-MM", Calendar.MONTH);
        sample.put("yyyyMM", Calendar.MONTH);
        sample.put("yy/MM", Calendar.MONTH);
        sample.put("yy-MM", Calendar.MONTH);
        sample.put("yyMM", Calendar.MONTH);
        sample.put("yyyyMMdd", Calendar.DATE);
        sample.put("yyyy-MM-dd", Calendar.DATE);
        sample.put("yyyy/MM/dd", Calendar.DATE);
        sample.put("yyMMdd", Calendar.DATE);
        sample.put("yy-MM-dd", Calendar.DATE);
        sample.put("yy/MM/dd", Calendar.DATE);
    }

    public DateUtils(){}

    public DateUtils(String pattern) {
        this.pattern = pattern;
        this.sdf = new SimpleDateFormat(pattern);
    }

    public String today() {
        return sdf.format(new Date());
    }

    public String previous(String date) throws Exception {

       try{
           Integer v = sample.getOrDefault(pattern, -1);
           calendar.setTime(sdf.parse(date));
           calendar.add(v, -1);
           return sdf.format(calendar.getTime());
       } catch (Exception e) {
           throw new Exception("table pattern  '"+ pattern +"' must be corresponding to table name suffix!");
       }

    }

    public static void main(String[] args) throws Exception {
        DateUtils du = null;
        try {
            du = new DateUtils("yyyy-MM");
        } catch (Exception e){
            System.out.println("table pattern '"+ du.pattern +"' must be date");
        }
        // System.out.println(du.pattern);
        // String y = du.previous("2019/01");
        String x = du.today();
        System.out.println(x);
    }

}
